package ru.alperez.gpsdub;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.json.JSONException;

import ru.alperez.gpsdub.adapter.ConflictListAdapter;
import ru.alperez.gpsdub.adapter.MainListAdapter;
import ru.alperez.gpsdub.transfer.DatabaseAdapter;
import ru.alperez.gpsdub.widget.CustomTabHost;
import ru.alperez.gpsdub.widget.SlidingViewFlipper;
import ru.alperez.model.ExtendedLocation;
import ru.alperez.model.GpsPoint;
import ru.alperez.model.LastFixState;
import ru.alperez.model.Result;
import ru.alperez.model.ResultSavePoint;
import ru.alperez.util.Converter;
import ru.alperez.util.CreatorManager;
import ru.alperez.util.CreatorManagerNoInitException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class GpsActivity extends Activity {
	private static final String TAG = "GpsDub";// test

	private static final boolean USE_NMEA = true;
	
	SlidingViewFlipper flipper;
	private CustomTabHost tabHost; 
	
	private TextView txtGpsTitle;
	private TextView txtCurrentLat;
	private TextView txtCurrentLon;
	private TextView txtCurrentAccuracy;
	private TextView txtCurrentSats;
	private TextView txtCurrentDateTime;
	private TextView txtPointCompareName;
	private TextView txtPointDistatce;	
	
	private EditText edtSaveLocationName;
	private EditText edtSaveLocationDescription;
	private TextView txtSaveLocationLatitude;
	private TextView txtSaveLocationLongitude;
	private TextView txtSaveLocationAltitude;
	private TextView txtSaveLocationAccuracy;
	private TextView txtSaveLocationNsat;
	private TextView txtSaveLocationProvider;
	private TextView txtSaveLocationCreatorName;
	private TextView txtSaveLocationCreatorDevice;
	private TextView txtSaveLocationCreatorImei;
	private TextView txtSaveLocationCreatorDesctiption;
	
	private View indicator;
	
	private Button btnGpsCompareClear;
	private Button btnGpsAddPoint;
	private Button btnSaveLocationSave;
	private Button btnSaveLocationCancel;
	
	private ListView listGpsPoints;
	private RelativeLayout listOverlay;
	
	private LocationManager locationManager;
	private ExtendedLocation currentGpsLocation;
	private LastFixState lastFixState = null;
	private GpsPoint referenceGpsPoint = null;
	private GpsPoint pointToSave = null;
	
	private DatabaseAdapter database;
	
	private List<GpsPoint> mainListCreationOrder = new ArrayList<GpsPoint>();
	private List<GpsPoint> mainListSortOrder = new ArrayList<GpsPoint>();
	private List<GpsPoint> mainListReference = new ArrayList<GpsPoint>();
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gps);
		
		flipper = (SlidingViewFlipper) findViewById(R.id.activity_gps_flipper);
		
		txtGpsTitle = (TextView)findViewById(R.id.gps_title);
		txtCurrentLat = (TextView)findViewById(R.id.gps_current_latitude);
		txtCurrentLon = (TextView)findViewById(R.id.gps_current_longtitude);
		txtCurrentAccuracy = (TextView)findViewById(R.id.gps_current_accuracy);
		txtCurrentSats = (TextView)findViewById(R.id.gps_sat_number);
		txtCurrentDateTime = (TextView)findViewById(R.id.gps_current_date_time);
		txtPointCompareName = (TextView)findViewById(R.id.gps_point_compare_name);
		txtPointDistatce = (TextView)findViewById(R.id.gps_point_compare_distance);
		
		indicator = (View)findViewById(R.id.gps_indicator);
		indicator.getBackground().setLevel(0);
		
		btnGpsCompareClear = (Button)findViewById(R.id.gps_clear_distance);
		btnGpsAddPoint = (Button)findViewById(R.id.gps_add_point);
		btnGpsAddPoint.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(currentGpsLocation != null) {
					try {
						pointToSave = new GpsPoint(currentGpsLocation, CreatorManager.getInstance().getCreator());
						pointToSave.setNsat(lastFixState.getNSat());
						goToSavePointScreen(pointToSave, true);
					} catch (CreatorManagerNoInitException e) {
						new AlertDialog.Builder(GpsActivity.this).setIcon(android.R.drawable.ic_dialog_alert)
						.setTitle(R.string.save_dialog_nocreator_title).setMessage(R.string.save_dialog_nocreator_message)
						.setPositiveButton(R.string.action_ok, null).create().show();
					}
				}
			}
		});
		
		btnSaveLocationSave = (Button) findViewById(R.id.btn_location_save_save);
		btnSaveLocationSave.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (pointToSave != null) {
					
					if (edtSaveLocationName.getText().length() == 0) {
						new AlertDialog.Builder(GpsActivity.this).setIcon(android.R.drawable.ic_dialog_alert)
						.setTitle(R.string.save_dialog_nocreator_title).setMessage(R.string.save_dialog_noname_message).setCancelable(false)
						.setPositiveButton(R.string.action_ok, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								if (tabHost != null) {
									tabHost.setCurrentTabByTag("name");
									edtSaveLocationName.requestFocus();
								}
							}
						}).create().show();
						return;
					}
					pointToSave.setName(edtSaveLocationName.getText().toString());
					pointToSave.setDescription(edtSaveLocationDescription.getText().toString());
					new SavePointTask(false).execute(pointToSave);
				}
			}
		});
		
		btnSaveLocationCancel = (Button) findViewById(R.id.btn_location_save_cancel);
		btnSaveLocationCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				pointToSave = null;
				flipper.setDisplayedChild(0);
			}
		});
		
		edtSaveLocationName = (EditText) findViewById(R.id.edt_save_location_name);
		edtSaveLocationDescription = (EditText) findViewById(R.id.edt_save_location_description);
		txtSaveLocationLatitude = (TextView) findViewById(R.id.txt_save_location_latitude);
		txtSaveLocationLongitude = (TextView) findViewById(R.id.txt_save_location_longitude);
		txtSaveLocationAltitude = (TextView) findViewById(R.id.txt_save_location_altitude);
		txtSaveLocationAccuracy = (TextView) findViewById(R.id.txt_save_location_accuracy);
		txtSaveLocationNsat = (TextView) findViewById(R.id.txt_save_location_nsat);
		txtSaveLocationProvider = (TextView) findViewById(R.id.txt_save_location_provider);
		txtSaveLocationCreatorName = (TextView) findViewById(R.id.txt_save_location_creator_name);
		txtSaveLocationCreatorDevice = (TextView) findViewById(R.id.txt_save_location_creator_device);
		txtSaveLocationCreatorImei = (TextView) findViewById(R.id.txt_save_location_creator_imei);
		txtSaveLocationCreatorDesctiption = (TextView) findViewById(R.id.txt_save_location_creator_description);
		
		tabHost = (CustomTabHost) findViewById(R.id.save_point_tabhost);
		tabHost.setup();
		tabHost.addTab(R.string.save_point_description, "name", R.id.point_description_container);
		tabHost.addTab(R.string.save_point_details, "details", R.id.point_data_container);
		
		listOverlay = (RelativeLayout) findViewById(R.id.gps_list_overlay);
		listOverlay.setVisibility(View.INVISIBLE);
		listGpsPoints = (ListView)findViewById(R.id.gps_list);
		listGpsPoints.setAdapter(new MainListAdapter(this, mainListReference));
		
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
			finish();
		}
		
		// --- Set CreatorManager ---
		SharedPreferences sPref = getSharedPreferences(getPackageName(), MODE_PRIVATE);
		String creatorName = sPref.getString("creator_name", null);
		String creatorDescr = sPref.getString("creator_description", null);
		if (creatorName==null || creatorDescr==null) {
			showSetCreatorDialog();
		} else {
			CreatorManager.getInstance().initialize(getApplicationContext(), creatorName, creatorDescr);
		}
		
		database = new DatabaseAdapter(this);
		
		new LoadPointsTask().execute();
	}
	
	private void showSetCreatorDialog() {
		Log.d(TAG, "showSetCreatorDialog() - start");
		final View content = getLayoutInflater().inflate(R.layout.creator_dialog_content, null);
		new AlertDialog.Builder(this).setTitle(R.string.creator_dialog_title).setView(content).setCancelable(false)
		.setNegativeButton(R.string.action_cancel, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				new AlertDialog.Builder(GpsActivity.this).setIcon(android.R.drawable.ic_dialog_info)
				.setTitle(R.string.creator_dialog_cancel_title).setMessage(R.string.creator_dialog_cancel_message)
				.setPositiveButton(R.string.action_ok, null).create().show();
			}
		})
		.setPositiveButton(R.string.action_ok, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String name = ((EditText) content.findViewById(R.id.creator_dialog_name)).getText().toString();
				String descr= ((EditText) content.findViewById(R.id.creator_dialog_description)).getText().toString();
				if (name.length()==0) {
					Log.d(TAG, "Creator name not provided");
					new AlertDialog.Builder(GpsActivity.this).setIcon(android.R.drawable.ic_dialog_alert)
					.setTitle(R.string.creator_dialog_error_title).setMessage(R.string.creator_dialog_error_message)
					.setCancelable(false).setPositiveButton(R.string.action_ok, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							showSetCreatorDialog();
						}
					}).create().show();
				} else {
					Log.d(TAG, "Creator data provided - init manager. Name - "+name+"; Descr - "+descr);
					SharedPreferences sPref = getSharedPreferences(getPackageName(), MODE_PRIVATE);
					sPref.edit().putString("creator_name", name).putString("creator_description", descr).commit();
					CreatorManager.getInstance().initialize(GpsActivity.this.getApplicationContext(), name, descr);
				}
			}
		}).create().show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_gps, menu);
		return true;
	}
	
	@Override
	public void onResume() {
		super.onResume();
		
		List<String> names = locationManager.getProviders(false);
		for (String name : names)
			Log.d(TAG, "LocationProvider - "+name+"  is "+((locationManager.isProviderEnabled(name)) ? "enabled" : "disabled"));
		
		if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 200, 0, locationListener);
			Log.d(TAG, "Add LocationListener");
			if (USE_NMEA) {
				locationManager.addNmeaListener(nmeaListener);
				Log.d(TAG, "Add NmeaListener");
			} else {
				
			}
		}
	}
	
	@Override
	public void onPause() {
		super.onPause();
		
		try{
			locationManager.removeUpdates(locationListener);
			Log.d(TAG, "Remove LocationListener");
			if (USE_NMEA) {
				locationManager.removeNmeaListener(nmeaListener);
				Log.d(TAG, "Remove NmeaListener");
			} else {
				
			}
		}catch (Exception e){
			Log.d(TAG, "~Exception remove LocationListener");
		}
	}
	
	@Override
	public void onBackPressed() {
		if (flipper.getDisplayedChild() > 0) {
			flipper.setDisplayedChild(0);
			return;
		}
		super.onBackPressed();
	}
	
	private void populateCurrentGpsData(ExtendedLocation currentLocation, LastFixState lastFixState, GpsPoint refGpsPoint) {
		if ((currentGpsLocation != null) && lastFixState.isFixed() && (System.currentTimeMillis()-lastFixState.getSysTime() < 5000)) { // Fixed
			txtGpsTitle.setText("YES");
			txtCurrentLat.setText( Converter.gpsLatitudeDMSFromLocation(currentLocation)+"\n"+Converter.gpsDegrees2String(currentLocation.getLatitude()) );
			txtCurrentLon.setText( Converter.gpsLongtitudeDMSFromLocation(currentLocation)+"\n"+Converter.gpsDegrees2String(currentLocation.getLongitude()) );
			txtCurrentAccuracy.setText("Acc: "+Converter.gpsAccuracyToString( currentLocation.getAccuracy() ));
			txtCurrentSats.setText("Sat: "+lastFixState.getNSat());
			txtCurrentDateTime.setText(Converter.gpsDateTimeFromLocation(currentLocation));
			if (refGpsPoint != null) {
				txtPointCompareName.setText(refGpsPoint.getOrder()+".  "+refGpsPoint.getName());
				txtPointDistatce.setText( Integer.toString((int)currentLocation.distanceTo(refGpsPoint.getLocation())) );
				btnGpsCompareClear.setEnabled(true);
			} else {
				txtPointCompareName.setText("");
				txtPointDistatce.setText("");
				btnGpsCompareClear.setEnabled(false);
			}
			btnGpsAddPoint.setEnabled(true);
			indicator.getBackground().setLevel(2);
		} else { // Not fixed
			txtGpsTitle.setText("NO");
			txtCurrentLat.setText("N/A");
			txtCurrentLon.setText("N/A");
			txtCurrentAccuracy.setText("Acc:");
			txtCurrentSats.setText("Sat: 0");
			txtCurrentDateTime.setText("N/A");
			if (refGpsPoint != null) {
				txtPointCompareName.setText(refGpsPoint.getOrder()+".  "+refGpsPoint.getName());
				txtPointDistatce.setText("N/A");
				btnGpsCompareClear.setEnabled(true);
			} else {
				txtPointCompareName.setText("");
				txtPointDistatce.setText("");
				btnGpsCompareClear.setEnabled(false);
			}
			btnGpsAddPoint.setEnabled(false);
			indicator.getBackground().setLevel(1);
		}
		indicator.postDelayed(new Runnable() {
			@Override
			public void run() {
				indicator.getBackground().setLevel(0);
			}
		}, 250);
	}

	
	private void goToSavePointScreen(GpsPoint point, boolean populateWithPoint) {
		if (populateWithPoint) {
			populateSavePointScreen(point);
			edtSaveLocationName.setText((point.getName() != null) ? point.getName() : "");
			edtSaveLocationDescription.setText((point.getDescription() != null) ? point.getDescription() : "");
		}
		
		tabHost.setCurrentTabByTag("details");
		btnSaveLocationSave.requestFocus();
		((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(flipper.getWindowToken() , 0);
		flipper.setDisplayedChild(1);
	}
	
	private void populateSavePointScreen(GpsPoint point) {
		try {
			txtSaveLocationLatitude.setText(Converter.gpsLatitudeDMSFromDegrees(point.getLocation().getLatitude()));
			txtSaveLocationLongitude.setText(Converter.gpsLongtitudeDMSFromDegrees(point.getLocation().getLongitude()));
			txtSaveLocationAltitude.setText(Converter.gpsAltitudeFromLocation(point.getLocation()));
			txtSaveLocationAccuracy.setText(Converter.gpsAccuracyToString(point.getLocation().getAccuracy()));
			txtSaveLocationNsat.setText(Integer.valueOf(point.getNsat()).toString());
			txtSaveLocationProvider.setText(point.getLocation().getProvider());
			txtSaveLocationCreatorName.setText(point.getCreator().getName());
			txtSaveLocationCreatorDevice.setText(point.getCreator().getDevice()+" ("+point.getCreator().getModel()+")");
			txtSaveLocationCreatorImei.setText(point.getCreator().getImei());
			txtSaveLocationCreatorDesctiption.setText(point.getCreator().getDescription());
		} catch (NullPointerException e) {
			txtSaveLocationLatitude.setText("N/A");
			txtSaveLocationLongitude.setText("N/A");
			txtSaveLocationAltitude.setText("N/A");
			txtSaveLocationAccuracy.setText("");
			txtSaveLocationNsat.setText("");
			txtSaveLocationProvider.setText("");
			txtSaveLocationCreatorName.setText("N/A");
			txtSaveLocationCreatorDevice.setText("");
			txtSaveLocationCreatorImei.setText("");
			txtSaveLocationCreatorDesctiption.setText("");
		}
	}
	
	private void setMainListDataSource() {
		//TODO Implement switching later
		mainListReference.clear();
		mainListReference.addAll(mainListCreationOrder);
	}
	
	private void showConflictResolveDialog(List<Map<String, Object>> conflicts) {
		if (conflicts == null || conflicts.size() == 0) {
			return;
		}
		ListView lv = new ListView(this);
		lv.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
		lv.setAdapter(new ConflictListAdapter(GpsActivity.this, conflicts));
		lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			
			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
				try {
					GpsPoint point = ((ConflictListAdapter.ConflictItemHolder) v.getTag()).getGpsPoint();
					Intent intent = new Intent(GpsActivity.this, PointDetailsViewActivity.class);
					try {
						intent.putExtra("location_point", point.toJSON().toString());
					} catch (JSONException e) {  }
					GpsActivity.this.startActivityForResult(intent, PointDetailsViewActivity.REQUEST_CODE);
				} catch (NullPointerException e) { }
				
			}
		});
		new AlertDialog.Builder(GpsActivity.this).setIcon(android.R.drawable.ic_dialog_alert).setTitle(R.string.save_dialog_conflicts_title).setView(lv)
				.setPositiveButton(R.string.action_ignore, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						new SavePointTask(true).execute(GpsActivity.this.pointToSave);
					}
				})
				.setNeutralButton(R.string.action_edit, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						GpsActivity.this.goToSavePointScreen(null, false);
					}
				})
				.setNegativeButton(R.string.action_cancel, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						GpsActivity.this.returnToMainForm();
					}
				}).setCancelable(false).create().show();
	}
	
	private void returnToMainForm() {
		if (GpsActivity.this.flipper.getDisplayedChild() > 0) {
			GpsActivity.this.flipper.setDisplayedChild(0);
		}
	}
	
	private final LocationListener locationListener = new LocationListener() {
		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			Log.d(TAG, "LocationListener::onStatusChanged. porvider="+provider+"; status="+status);
		}
		
		@Override
		public void onProviderEnabled(String provider) {
			Log.d(TAG, "LocationListener::onProviderEnabled");
		}
		
		@Override
		public void onProviderDisabled(String provider) {
			Log.d(TAG, "LocationListener::onProviderDisabled");
		}
		
		@Override
		public void onLocationChanged(Location location) {
			Log.d(TAG, "LocationListener::onLocationChanged");
			currentGpsLocation = new ExtendedLocation((ExtendedLocation) location);
			if (!USE_NMEA) {
				populateCurrentGpsData(currentGpsLocation, lastFixState, referenceGpsPoint);
			}
		}
	};
	
	private final GpsStatus.Listener gpsStatusListener = new GpsStatus.Listener() {
		@Override
		public void onGpsStatusChanged(int event) {
			
		}
	};
	
	private final GpsStatus.NmeaListener nmeaListener = new GpsStatus.NmeaListener() {
		@Override
		public void onNmeaReceived(long timestamp, String nmea) {
			if (nmea.startsWith("$GPGGA")) {
				lastFixState = new LastFixState(nmea);
				Log.d(TAG, nmea+(lastFixState.isFixed()?"   Fixed":"   NON fixed"));
				if (!lastFixState.isFixed()) currentGpsLocation = null;
				populateCurrentGpsData(currentGpsLocation, lastFixState, referenceGpsPoint);
			}
		}
	};

	//---------------------------------------------------------------------------------
	/**
	 * 
	 * @author admin
	 *
	 */
	private class LoadPointsTask extends AsyncTask<Void, Void, String> {
		@Override
		protected void onPreExecute() {
			listOverlay.setVisibility(View.VISIBLE);
		}
		
		@Override
		protected String doInBackground(Void... params) {
			long tStart = System.currentTimeMillis();
			String ret = null;
			try {
				database.openRead();
				mainListCreationOrder = database.selectPoints();
			} catch (Exception e) {
				ret = "Error load from DB - "+e.getMessage();
			} finally {
				database.close();
			}
			long dt = System.currentTimeMillis() - tStart;
			if (dt < 400) {
				try {
					Thread.sleep(400 - dt);
				} catch (Exception e){}
			}
			return ret;
		}
		
		@Override
		protected void onPostExecute(String result) {
			listOverlay.setVisibility(View.INVISIBLE);
			if (result != null) {
				Toast.makeText(GpsActivity.this, result, Toast.LENGTH_SHORT).show();
				((MainListAdapter)listGpsPoints.getAdapter()).clear();
			} else {
				setMainListDataSource();
				((MainListAdapter)listGpsPoints.getAdapter()).notifyDataSetChanged();
			}
			if (GpsActivity.this.flipper.getDisplayedChild() > 0) {
				GpsActivity.this.flipper.setDisplayedChild(0);
			}
		}
	}
	
	//---------------------------------------------------------------------------------------------
	/**
	 * 
	 * @author admin
	 *
	 */
	private class SavePointTask extends AsyncTask<GpsPoint, Void, Result> {
		private ProgressDialog progressDialog;
		private boolean saveAnyway;

		public SavePointTask(boolean saveAnyway) {
			super();
			this.saveAnyway = saveAnyway;
		}
		
		@Override
		protected void onPreExecute() {
			progressDialog = new ProgressDialog(GpsActivity.this);
			progressDialog.setMessage(getString(R.string.action_saving));
			progressDialog.show();
		}

		@Override
		protected Result doInBackground(GpsPoint... params) {
			long tStart = System.currentTimeMillis();
			String result = null;
			database.openWrite();
			try {
				Result rez = database.insertPoint(params[0]);
				
				if (rez.getResult()) {
					result = "Saved.";
				} else {
					result = "Error save location! "+rez.getErrorString();
				}
			} finally {
				database.close();
			}
			long dt = System.currentTimeMillis() - tStart;
			if (dt < 500) {
				try {
					Thread.sleep(500 - dt);
				} catch (Exception e){}
			}
			return result;
		}

		@Override
		protected void onPostExecute(Result result) {
			if (progressDialog != null) {
				progressDialog.dismiss();
			}
			
			
			if (result.getResult()) { // Unique point
				Toast.makeText(GpsActivity.this, result.getErrorString(), Toast.LENGTH_SHORT).show();
				GpsActivity.this.returnToMainForm();
				new LoadPointsTask().execute();
			} else { // Some error or conflict
				if (result.getErrorCode() == Result.ErrorCode.ERROR_CONFLICT) { // Conflict with already saved points
					if (((ResultSavePoint) result).isSavedWithConflict()) { // Saved, but with conflicts
						Toast.makeText(GpsActivity.this, result.getErrorString(), Toast.LENGTH_SHORT).show();
						GpsActivity.this.returnToMainForm();
						new LoadPointsTask().execute();
					} else { // Not saved yet
						GpsActivity.this.showConflictResolveDialog(((ResultSavePoint) result).getConflicts());
					}
				} else { // Some error not about conflict
					Toast.makeText(GpsActivity.this, result.getErrorString(), Toast.LENGTH_SHORT).show();
					GpsActivity.this.returnToMainForm();
				}
			}
		}
		
	}
	
	
	/*private class SavePointTask extends AsyncTask<GpsPoint, Void, String> {
		private ProgressDialog progressDialog;

		@Override
		protected void onPreExecute() {
			progressDialog = new ProgressDialog(GpsActivity.this);
			progressDialog.setMessage(getString(R.string.action_saving));
			progressDialog.show();
		}

		@Override
		protected String doInBackground(GpsPoint... params) {
			long tStart = System.currentTimeMillis();
			String result = null;
			database.openWrite();
			try {
				Result rez = database.insertPoint(params[0]);
				
				if (rez.getResult()) {
					result = "Saved.";
				} else {
					result = "Error save location! "+rez.getErrorString();
				}
			} finally {
				database.close();
			}
			long dt = System.currentTimeMillis() - tStart;
			if (dt < 500) {
				try {
					Thread.sleep(500 - dt);
				} catch (Exception e){}
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			if (progressDialog != null) {
				progressDialog.dismiss();
			}
			Toast.makeText(GpsActivity.this, result, Toast.LENGTH_SHORT).show();
			if (GpsActivity.this.flipper.getDisplayedChild() > 0) {
				GpsActivity.this.flipper.setDisplayedChild(0);
			}
			new LoadPointsTask().execute();
		}*/

}
